package com.ruoyi.system.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.AsyncDetail;
import com.ruoyi.system.domain.SmsAccount;
import com.ruoyi.system.domain.SmsDetail;
import com.ruoyi.system.service.IAliSmsService;
import com.ruoyi.system.service.IAsyncDetailService;
import com.ruoyi.system.service.ISmsAccountService;
import com.ruoyi.system.service.ISmsDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class AliSmsServiceImpl implements IAliSmsService {

    @Autowired
    private ISmsDetailService smsDetailService;
    @Autowired
    private ISmsAccountService messageAccountService;
    @Autowired
    private IAsyncDetailService asyncDetailService;

    //产品请求url
    private static final String BASE_URL = "dysmsapi.aliyuncs.com";

    @Value("${notification.sms.keyId:}")
    private String keyId;

    @Value("${notification.sms.secret:}")
    private String secret;

    @Value("${notification.sms.signName:}")
    private String signName;

    @Value("${notification.sms.template.alarm:}")
    private String alarmTemplate;

    @Override
    public SmsAccount getAccount() {
        //查询总账户
        SmsAccount smsAccount = messageAccountService.getMessageAccount(new SmsAccount());
        if (smsAccount == null) {
            smsAccount = messageAccountService.getCompanyOne(new SmsAccount());
            if (smsAccount == null) {
                throw new CustomException("没有查询到账户配置信息");
            }
        }
        return smsAccount;
    }

    @Override
    @Async
    public void send(JSONObject request, String tid) {
        Long companyId = request.getLong("companyId");
        String receivers = request.getString("receivers");
        String type = request.getString("type");
        String template = null;
        if ("alarm".equals(type)) {
            template = alarmTemplate;
        } else {
            // TODO: [zy]
            return;
        }
        JSONObject parameters = request.getJSONObject("parameters");
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", keyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest requestResult = new CommonRequest();
        //产品请求url
        requestResult.setSysDomain(BASE_URL);
        requestResult.setSysAction("SendSms");
        //版本
        requestResult.setSysVersion("2017-05-25");
        requestResult.putQueryParameter("TemplateCode", template);
        requestResult.putQueryParameter("PhoneNumbers", receivers);
        requestResult.putQueryParameter("SignName", signName);
        requestResult.putQueryParameter("TemplateParam", parameters.toJSONString());
        log.info("{}", requestResult.getSysQueryParameters());
        CommonResponse addSmsTemplateResponse = null;
        boolean flag = false;
        try {
            addSmsTemplateResponse = client.getCommonResponse(requestResult);
        } catch (Exception e) {
            log.error("短信发送失败。异常原因{}", e.getMessage());
            //throw new CustomException("短信发送失败。异常原因:" + e.getMessage());
            flag = true;
            asyncDetailService.update(tid, 2, "短信发送失败。失败原因:" + e.getMessage());
        }
        SmsDetail detail = new SmsDetail();
        JSONObject jsonObject = null;
        if (addSmsTemplateResponse != null && addSmsTemplateResponse.getData() != null && JSONObject.parseObject(addSmsTemplateResponse.getData()) != null) {
            String data = addSmsTemplateResponse.getData();
            log.info("短信发送返回结果：{}", data);
            jsonObject = JSONObject.parseObject(data);
            //发送回执ID
            detail.setBizId(jsonObject.getString("BizId"));
            detail.setRequestId(jsonObject.getString("RequestId"));
            detail.setCode(jsonObject.getString("Code"));
            detail.setMessage(jsonObject.getString("Message"));
        }else {
            //发送失败
            if (!flag){
                flag = true;
                asyncDetailService.update(tid, 2, "短信发送失败。失败原因：没有获取到短信返回值");
            }
        }
        detail.setPhoneNumbers(receivers);
        detail.setTemplateParam(parameters.toJSONString());
        detail.setTemplateCode(template);
        detail.setType(type);
//        detail.setCreateBy(userName);
        detail.setCompanyId(companyId);
        detail.setCreateTime(new Date());
        detail.setTid(tid);
        //保存短信明细数据
        smsDetailService.addMessageDetail(detail);
        //更新异步数据详情
        if (!flag){
            asyncDetailService.update(tid, 1, JSONUtil.toJsonStr(jsonObject));
        }
    }

//     @Override
//     public void sendBatchSms(SmsAccount smsAccount, Integer alarmId, String templateCode, List<String> phoneNumberList, Map<String, Object> params) {
//         if (CollectionUtils.isEmpty(phoneNumberList) || StringUtils.isEmpty(templateCode) || smsAccount == null) {
//             throw new CustomException("发送人手机号或短信模板或账户配置信息不能为空");
//         }
//         DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsAccount.getKeyId(), smsAccount.getSecret());
//         IAcsClient client = new DefaultAcsClient(profile);
//         CommonRequest request = new CommonRequest();
//         request.setSysDomain(BASE_URL);
//         request.setSysAction("SendBatchSms");
//         //版本
//         request.setSysVersion("2017-05-25");
//         request.putQueryParameter("TemplateCode", templateCode);
//         request.putQueryParameter("PhoneNumberJson", JSON.toJSONString(phoneNumberList));
//         request.putQueryParameter("SignNameJson", smsAccount.getSignName());
//         request.putQueryParameter("TemplateParamJson", JSON.toJSONString(params));
//         CommonResponse addSmsTemplateResponse = null;
//         try {
//             addSmsTemplateResponse = client.getCommonResponse(request);
//         } catch (Exception e) {
//             log.error("短信发送失败。异常原因{}", e.getMessage());
//             throw new CustomException("短信发送失败。异常原因:" + e.getMessage());
//         }
//         if (addSmsTemplateResponse == null) {
//             throw new CustomException("短信发送异常");
//         }
//         String data = addSmsTemplateResponse.getData();
//         log.info("短信发送返回结果：{}", data);
//         JSONObject jsonObject = JSONObject.parseObject(data);
//         SmsDetail detail = new SmsDetail();
//         for (int i = 0; i < jsonObject.size(); i++) {
//             //发送回执ID
//             detail.setBizId(jsonObject.getString("BizId"));
//             detail.setRequestId(jsonObject.getString("RequestId"));
//             detail.setCode(jsonObject.getString("Code"));
//             detail.setMessage(jsonObject.getString("Message"));
//         }
//         detail.setPhoneNumber(phoneNumberList.toString());
//         detail.setTemplateParam(JSON.toJSONString(params));
//         detail.setTemplateCode(templateCode);
//         detail.setAlarmId(alarmId);
// //        detail.setCreateBy(userName);
// //        detail.setCompanyId(companyId);
//         //保存短信明细数据
//         messageDetailService.addMessageDetail(detail);
//     }

}
